/*===== code build by mstore0.1.3 =====*/

/*===== common/xz#pagination:0 =====*/

$$('pagination', function(){
    
    var DEFAULT_ID = '#jqPagination0'; //默认id
    var DEFAULT_BTN_COUNT = 9; //默认按钮个数
    
    return function(id, callback, option){
        
        if(typeof id == 'function'){ //只传一个参数，默认id
            option = callback;
            callback = id;
            id = DEFAULT_ID;
        }
        
        option = option || {};
        var $container = $(id);
        if(option.pageStyle){
            $container.addClass(option.pageStyle);
        }
        
        var pageOption = $container.attr('data-option').split(',');
        var ITEM_COUNTS = +pageOption[0]; //总个数
        var PAGE_SIZE = +pageOption[1]; //分页条数
        var PAGE_FOCUS = +pageOption[2]; //当前选中页
        var PAGE_COUNT = Math.ceil(ITEM_COUNTS / PAGE_SIZE); //页码总数
        var BUTTON_COUNTS = option.btnCount || DEFAULT_BTN_COUNT; //显示按钮个数
        
        var curpage = PAGE_FOCUS;
        
        $container = $container.html('<div class="inner"></div>');
        
        render();
        
        bindClick($container);
        
        return {
            reload: function(data_option){
                $container.attr('data-option', data_option);
                var pageOption = data_option.split(',');
                ITEM_COUNTS =+ pageOption[0];
                PAGE_SIZE =+ pageOption[1];
                PAGE_FOCUS =+ pageOption[2];
                PAGE_COUNT =+ Math.ceil(ITEM_COUNTS / PAGE_SIZE);
                
                curpage = PAGE_FOCUS;
                
                render();
            }
        }
        
        function bindClick(container){
            container.on('click', '[jq_pagination_button]', function(){
                var index = $(this).attr('jq_pagination_button');
                if(index == 'next'){
                    if(curpage < PAGE_COUNT){
                        focus(curpage + 1);
                    }
                }else if(index == 'prev'){
                    if(curpage > 0){
                        focus(curpage - 1);
                    }
                }else if(index == 'goto'){
                    var newpage = parseInt($container.find('input').val());
                    if(newpage > 0 && newpage <= PAGE_COUNT){
                        focus(newpage);
                    }else{
                        alert('请输入正确的页数');
                    }
                }else if(index != curpage){
                    focus(+index);
                }
            });
        }
        
        function render(){
            var
            SIZE = BUTTON_COUNTS,
            TOTAL = PAGE_COUNT,
            current = curpage,
            offset = SIZE / 2,
            prev = '',
            next = '',
            header = '', //头部点
            tailer = '', //尾部点
            body = '',
            numSize = SIZE, //中间部分数字长度
            num, //中间开始页码
            i = 0;
            
            
            
            //如果当前页是首页
            prev = current == 1 ? '<span class="prev dis">上一页</span>' : '<span class="prev" jq_pagination_button="prev">上一页</span>';
            //如果当前页是最后一页
            next = current == TOTAL ? '<span class="next dis"></span>' : '<span class="next" jq_pagination_button="next">下一页</span>';
            
            if(TOTAL > SIZE){//页码总数大于按钮个数，有左右点
                if(current > offset){ //有左点dot
                    header = '<span class="num" jq_pagination_button="1">1</span><span class="dot">...</span>';
                    numSize -= 2;
                }
                if((TOTAL - current) > (offset - 1)){ //有右点dot
                    tailer = '<span class="dot">...</span><span class="num" jq_pagination_button="'+TOTAL+'">'+TOTAL+'</span>';
                    numSize -= 2;
                }
            }else{
                numSize = Math.min(numSize, TOTAL);
            }
            
            num = //中间部分数字
            header && tailer //左右都有点
            ? current - ~~(numSize/2) 
            : tailer 
                ? 1 //只有尾部有点
                : TOTAL + 1 - numSize; //只有头部有点
            
            while(numSize--){
                body += num == current //当前页面
                    ? '<span class="num cur">'+num+'</span>'
                    : '<span class="num" jq_pagination_button="'+num+'">'+num+'</span>';
                    num++;
            }
            
            var info = [
                '<span class="info">共'+ TOTAL +'页</span>',
                '<span class="goto">到第<input>页<button jq_pagination_button="goto">确定</button></span>'
            ].join('');
            
            
            $container.find('.inner').html([prev, header, body, tailer, next, info]);
            
            if(TOTAL > 1){
                $container.show();
            }else{
                $container.hide();
            }
        }
        
        function focus(index){
            callback(curpage = index);
            render();
        }
        
    };
});

/*===== common/xz#topbar:0 =====*/

$(document).on('click', '[xzclick="toLogin"]', function(){
    location = '/login.htm?backUrl='+ location.href;
});

$$.domready('.topbar', function(){
    
    $.getJSON('/jsonislogin.json?callback=?', function(data){
        if(data.userNick){
            var user = decodeURI(decodeURI(data.userNick));
            if(user.length > 13){
                user = user.substr(0, 10) + '...';
            }
            $('.topbar .loginBox').html('<span>你好，</span><a class="userName" href="/seller/index.htm">'+ user +'</a><a href="/membertc.htm">退出</a>');
        }else{
            $('.topbar .loginBox').html('<span>你好，</span><em>请 </em><a class="simpleLogin" xzclick="toLogin">登录</a><a href="http://www.571xz.com/regedit.htm"  target="_blank">注册</a><a class="tbLogin" href="http://www.571xz.com/ortherLogin.htm?ortherLoginType=1">淘宝登录</a>');
        }
    });
    if(window.webSite){
        $.getJSON('/marketDataList.json?callback=?', {webSite:webSite || ''}, function(resp){
            $('.webNav ul').html($rtpl(function(){/*
                {{{each webNavs as market}}}
                <li><a href="http://{{{market.webSite}}}.571xz.com/market.htm?mid={{{market.mid}}}">{{{market.marketName}}}</a></li>
                {{{/each}}}
            */},{webNavs: resp}));
        });
    }
    $('.cnBox').hover(function(){
        $(this).parent().prev().find('.cgcom').css('border-right','1px solid transparent');
    },function(){
        $(this).parent().prev().find('.cgcom').css('border-right','1px solid #d8d8d8');
    });
    
});

/*===== common/xz#search:0 =====*/

$$.search = function(){
    var $container;
    var href = location.href.split('#')[0].split('?')[0];
    
    $(function(){
         $container = $('#wgt_search');
    });
    
    search.set = function(name, value){
        if(typeof name == 'object'){
            $.each(name, search.set);
        }else{
            $container.find('input[name='+ name +']').val(value);
        }
    };

    search.get = function(name){
        if(name == null || name === true){
            var datas = {};
            $container.find('input').each(function(){
                if(name === true && !/^\s*$/.test(this.value) || name == null){
                    datas[this.name] = this.value;
                }
            });
            return datas;
        }else{
            return $container.find('input[name='+ name +']').val();
        }
    };

    search.bind = function(selector, keyset){
        $(document).on('click', selector, function(){
            var data = {};
            $.each(keyset, function(name, item){
                if(typeof item == 'function'){
                    data[name] = item();
                }else{
                    data[name] = $(item).val();
                }
            });
            search(data);
        });
    };
    
    return search;
    
    function search(callback, option){
        option = option || {};
        //console.info(search.get());
        var data =  search.get(); //默认数据
        if(typeof callback == 'function'){
            var newdata = callback(data); //修改返回的数据
        }else if(typeof callback == 'object'){ //传入的是对象，则添加到数据到默认的数据
            $.each(callback, function(name, value){
                data[name] = value; 
            });
        }
        
        var senddata = newdata || data; //当没有返回数据时，使用data数据，即data可能会在callback中已经发生修改
        var param = [];
        $.each(senddata, function(name, value){
            if(!/^\s*$/.test(value) && value != null){
                param.push(name +'='+ value);
            }
        });
        param = param.length ? '?'+ param.join('&') : '';
        location.href = (option.href || href) + param;
        
    }
}();

/*===== common/xz#searchBar:0 =====*/

$(function(){
    $('.searchBar .tabList li').click(function(){
        var $that = $(this);
        if(!$that.hasClass('select')){
            $that.addClass('select').siblings().removeClass('select');
            $('#formSearch').attr('action', {
                goods:'http://so.571xz.com/'+ webSite +'search.htm',
                store:'http://www.571xz.com/storenum.htm'
            }[$that.attr('type')])
            
            if($that.attr('type') == 'store'){
                if(!($('.searchWeb')[0])){
                    $('#formSearch').append('<input class="searchWeb" type=hidden name="webSite" value="'+ webSite +'">');
                }
            }else{
                if($('.searchWeb')[0]){
                    $('.searchWeb').remove();
                }
            }
            
            $('#formSearch input[name=keyword]').attr('placeholder', {
                goods:'输入商品名称',
                store:'输入档口号进行查询'
            }[$that.attr('type')]);
        }
    });
    
    $('#formSearch').on('submit', function(){
        if($('.searchCon').val() != ""){
            if($('.searchBar input[name=pid]')[0]){
                $('.searchBar input[name=pid]').remove();
            }
        }
    });
    
});

/*===== common/xz#openTaobaoShop:0 =====*/

$(document).on('click', '[xzclick=openTaobaoShop]', function(){
    open($(this).attr('data-href'));
});

/*===== common/base#pipe:0 =====*/


function $pipe(exports){
    
    var slice = [].slice;
    var main = exports.main;
    var onError = exports.error;
    var onEnd = exports.end;
    var noCatch = exports.noCatch;
    var endTimer;
    
    exports.main = exports.error = exports.end = exports.noCatch = null;
    
    var $fns = {};
    var $data = {}; 
    var $exports = {};
    var $queue = [];
    var $wait = false;
    var $end = false;
    var $error = false;
    
    $exports.$stop = function(){
        info('stop');
        $wait = true;
    };
    
    $exports.$continue = function(){
        if(!$wait){
            return;
        }
        info('continue');
        $wait = false;
        var option;
        var $queueCopy = $queue.slice(0);
        $queue = [];
        while(option = $queueCopy.shift()){
            $exports[option.name].apply($data, option.args);
        }
    };
    
    $exports.$end = function(){
        $end = true;
    };
    
    $exports.$info = function(msg){
        info(msg);
    };
    
    $exports.$domready = function(){
        $exports.$stop();
        $(function(){
            $exports.$continue();
        });
        return $exports;
    };
    
    $exports.$error = function(msg){
        error(new Error(msg));
    };
    
    for(var key in exports){
        var item = exports[key];
        if(typeof item == 'function'){
            $fns[key] = item;
            $exports[key] = function(key){
                return function(){

                    if($end || $error){
                        return $exports;
                    }

                    var args = slice.call(arguments);
                    args.push($exports, $data);
                    
                    var option = {name:key, args: args};
                    if($wait){
                        $queue.push(option);
                    }else{
                        run(option);
                    }
                    
                    return $exports;
                };
            }(key);
        }else if(item != null){
            $data[key] = item;
        }
    }
    
    main.call($data, $exports, $data);
    
    function run(option){
        if(noCatch){
            $fns[option.name].apply($data, option.args);
            listenEnd();
        }else{
            try{
                $fns[option.name].apply($data, option.args);
                listenEnd();
            }catch(err){
                error(err);
            }  
        }
    }
    
    function info(msg){
        /pipeinfo=1/.test(location.search) && console.info('$pipe => '+ msg);
    }
    
    function error(err){
        $error = true;
        $data.error = err;
        onError && onError(err);
    }
    
    function listenEnd(){
        clearTimeout(endTimer);
        endTimer = setTimeout(function(){
            onEnd && onEnd.call($data, $exports, $data);
            $end = $error = null; //重置流程
        });
    }
    
}

/*===== common/xz#user:0 =====*/

$xz('user', function(){
    
    var hasLogin = false;
    var userInfo = {};
    return {
        isLogin: isLogin,
        toLogin: toLogin,
        end: null
    };
    
    function isLogin(success, failure){
        if(hasLogin){
            success(userInfo);
        }else{
            $.getJSON(main_host +'jsonislogin.action?callback=?', function(data){
                if(data.userNick != undefined){
                    hasLogin = true;
                    userInfo.user = decodeURI(decodeURI(data.userNick));
                    userInfo.userId = data.userId;
                    userInfo.userType = data.userType; //拼音简写，供应商为gys;分销商为fxs
                    success(userInfo);
                }else{
                    failure && failure();
                }
            }); 
        }
    }
    
    function toLogin(option){
        option = option || {};
        option.type = option.type || 'JUMP';
        if(option.type == 'JUMP'){ //跳走当前页
            location.href = main_host + 'login.htm?backUrl='+ location.href;
        }
    }
    
});

/*===== common/xz#addGoodsData:0 =====*/

$(document).on('click', '[xzclick=addGoodsData]', function(){
    var $button = $(this);
    $pipe({
        main: function(pipe){
            pipe
                .isLogin() //先从缓存中判断登录
                .sendAjax() //提交操作
                ;
        },
        isLogin: function(pipe){
            pipe.$stop();
            $xz.user.isLogin(function(userInfo){
                if(userInfo.userType == 'gys'){
                    $$.window.open($rtpl(function(){/*
                        <div class="msgbox fs14">请登录分销商账号！</div>
                        <div class="buttonbox">
                            <b jbtn="jqWindow.close" class="ok">我知道了</b>
                        </div>
                    */}), {
                        title: '提示',
                        clsName: 'windowStyle'
                    }); 
                }else{
                    pipe.$continue();
                }
            }, function(){
                //未登录
                $$.loginWindow.open();
                //$xz.user.toLogin();
            });
        },
        sendAjax: function(){
            if(!($button.attr('data-goodsid'))){
                window.console && console.info && console.info('添加数据包goodsid不存在');
            }
            $.getJSON(
                main_host +"jsonScAddGoods.json?callback=?",
                {'goodsId':$button.attr('data-goodsid')},
                function(data){
                    if(data.result == 'success'){
                        $$.alert('添加成功，可以在会员中心查看');
                    }else{
                        if(data.msg == '2'){
                            $$.alert("您已收藏该商品");
                        }else{
                            $xz.user.toLogin();
                        }
                    }
                }
            );
        }
    });
    
});
